#include "Profiler.h"
#include "logger/Logger.h"
#include "platform/Platform.h"

namespace easy2d {

#define INFO_FORMAT	" %u msec (%u sceond)"

	FuncProfiler::FuncProfiler(const char* log, uint timeout /* = 0 */)
	{
		m_timeout = timeout;
		if (log == NULL) {
			m_strLog = "";
		} else {
			m_strLog = log;
		}

		m_lastTick = Platform::clock();
	}


	FuncProfiler::~FuncProfiler()
	{
		if (m_strLog.length() > 0) {
			uint curTick = Platform::clock();
			uint elapse = curTick - m_lastTick;

			char temp[256];
			float second = (float)elapse/1000.0f;
			sprintf(temp, INFO_FORMAT, elapse, (uint)second);
			m_strLog += temp;

			if (elapse >= m_timeout) {
				LOGI(m_strLog.c_str());
			}
		}
	}


	//////////////////////////////////////////////////////////////////////////


	Profiler::Profiler(void)
	{
		m_isLogOpened = true;
		m_timeout = 0;
		m_lastTick = Platform::clock();
	}

	Profiler::~Profiler(void)
	{
	}

	void Profiler::begin()
	{
		stPF item;
		item.lastTick = Platform::clock();
		m_fpItems.push(item);
	}

	void Profiler::end(const char* log, uint timeout /* = 0 */)
	{
		if (m_fpItems.empty()) {
			LOGI("[!!!]Profiler not match");
			return;
		}

		stPF& item = m_fpItems.top();
		uint curTick = Platform::clock();
		uint elapse = curTick - item.lastTick;

		m_fpItems.pop();

		if (log == NULL)
			return;

		if (!m_isLogOpened)
			return;

		char temp[256];
		float second = (float)elapse/1000.0f;
		sprintf(temp, INFO_FORMAT, elapse, (uint)second);
		std::string strLog = log;
		strLog += temp;

		uint timeTmp = timeout > 0 ? timeout : m_timeout;
		if (elapse >= timeTmp) {
			LOGI(strLog.c_str());
		}
	}

}	// namespace


